<template>
  <div id="url-picture-upload">
    <a-input-group compact style="margin-bottom: 16px" >
      <a-input v-model:value="fileUrl" style="width: calc(100% - 120px)" placeholder="请输入图片URL" />
      <a-button :loading="loading" type="primary" @click="handleUpload" style="width:120px">提交</a-button>
    </a-input-group>
    <img v-if="picture?.url" :src="picture?.url" alt="avatar">
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { uploadPictureByUrlUsingPost } from '@/request/api/pictureController.ts'

// Props类型
interface Props {
  spaceId?: any
  picture?: API.PictureVO
  onSuccess?: (newPicture: API.PictureVO) => void
}
const props = defineProps<Props>()
const loading = ref<boolean>(false)
const fileUrl  = ref<string>('')

// 上传成功的钩子函数
const handleUpload = async ({ file }: any) => {
  try {
    // 通过url的方式上传
    const params:API.PictureUploadRequest={fileUrl:fileUrl.value}
    params.spaceId=props.spaceId;
    // 有图片时表示图片上传成功，那么接下去需要更新图片信息
    if (props.picture) {
      params.id = props.picture.id
    }
    console.log(props.spaceId)
    const { data:res } = await uploadPictureByUrlUsingPost(params)
    if (res.code === 0 && res.data) {
      // 上传成功
      message.success('上传成功')
      // 将信息返回给父组件
      props.onSuccess?.(res.data)
    } else {
      // 上传失败
      message.error('上传失败' + res.message)
    }
  } catch (e) {
    // 上传失败
    message.error('上传失败' + e)
  } finally {
    loading.value=false
  }
}

</script>
<style lang="less" scoped>
#url-picture-upload {
  img {
    align-content: center;
    max-width: 100%;
    max-height: 480px;
  }
}
</style>
